package com.ruoyi.pill.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.OSinfo;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.pill.domain.SystemMysqlBackups;
import com.ruoyi.pill.mapper.SystemMysqlBackupsMapper;
import com.ruoyi.pill.service.SystemMysqlBackupsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;

@Service
public class SystemMysqlBackupsServiceImpl implements SystemMysqlBackupsService {


    @Resource
    private SystemMysqlBackupsMapper systemMysqlBackupsMapper;

    @Value("${spring.datasource.win-path}")
    private String windowsPath;

    /**
     * Linux数据库备份地址
     */
    @Value("${spring.datasource.linux-path}")
    private String linuxPath;

    @Value("${spring.datasource.mac-path}")
    private String macPath;

    @Override
    public SystemMysqlBackups selectLatestRecord() {
        return systemMysqlBackupsMapper.selectBackupList().get(0);
    }

    @Override
    public void save(SystemMysqlBackups backups) {
        systemMysqlBackupsMapper.insertSystemMysqlBackups(backups);
    }

    @Override
    public Object rollback(SystemMysqlBackups smb, String userName, String password) {
        String path ;
        // 备份路径和文件名
        if (OSinfo.isWindows()){
            path = windowsPath;
        }else if (OSinfo.isLinux()){
            path = linuxPath;
        }else {
            path = macPath;
        }
        StringBuilder realFilePath = new StringBuilder().append(path).append(smb.getName());
        if (!new File(realFilePath.toString()).exists()) {
            return AjaxResult.error(HttpStatus.NOT_FOUND.value(), "文件不存在，恢复失败，请查看目录内文件是否存在后重新尝试！");
        }
        StringBuilder cmd = new StringBuilder()
                .append("mysql -h")
                .append("127.0.0.1")
                .append(" -u")
                .append(userName)
                .append(" -p")
                .append(password)
                .append(" ")
                .append("db_pss")
                .append(" < ")
                .append(realFilePath);
        String[] command = new String[0];
        // 获取操作系统名称
//        String osName = System.getProperty("os.name").toLowerCase();
        if (OSinfo.isWindows()) {
            // Windows
            command = new String[]{"cmd", "/c", String.valueOf(cmd)};
        } else if (OSinfo.isLinux()){
            // Linux
            command = new String[]{"/bin/sh", "-c", String.valueOf(cmd)};
        }else if (OSinfo.isMacOS() || OSinfo.isMacOSX()){
            command  = new String[]{"/bin/bash","-c", String.valueOf(cmd)};
        }
        // 恢复指令写入到数据库
        smb.setCmd(String.valueOf(cmd));
        // 更新操作次数
        smb.setCreateTime(new Date());
//        smb.setOperation(smb.getOperation() + 1);
        // 获取Runtime实例
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            if (process.waitFor() == 0) {
                return smb;
            } else {
                return AjaxResult.error(HttpStatus.GATEWAY_TIMEOUT.value(), "网络异常，恢复失败，请稍后重新尝试！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(HttpStatus.GATEWAY_TIMEOUT.value(), "网络异常，恢复失败，请稍后重新尝试！");
        }

    }
}
